<?php

namespace app\admin\common\controller;

use app\admin\framework\api\Permission;
use app\common\model\Dept;

#[Permission('部门管理', 'System', 10001)]
class DeptController
{
    private $model;
    
    public function __construct(){
        $this->model = new Dept();
    }
    
    #[Permission('参数')]
    public function option()
    {
        return apiSuccess(data: [
            'status' => ['禁用', '正常'],
        ]);
    }
    
    #[Permission('详情')]
    public function detail()
    {
        $id = request()->get('id', 0);
        $result = $this->model->where('id', $id)->find()->toArray();
        return apiSuccess(data: $result);
    }
    
    #[Permission('查询')]
    public function select()
    {
        $data = request()->get();
        $result = $this->model->where(function ($query) use ($data) {
            if (!empty($data['keyword'])) {
                $query->where('name', 'like', '%' . $data['keyword'] . '%');
            }
            if (!empty($data['address'])) {
                $query->where('address_id', $data['address']);
            }
            if (isset($data['status'])) {
                $query->where('status', $data['status']);
            }
        })->order('id asc')->select();
        return apiSuccess(data: ['list' =>  $result, 'total' => count($result)]);
    }
    
    #[Permission('创建')]
    public function create()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            $this->model->save($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }
    
    #[Permission('更新')]
    public function update()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            $this->model->update($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }
    
    #[Permission('快捷修改')]
    public function speed()
    {
        if (setFieldUpdate($this->model)) {
            return apiSuccess('修改成功');
        } else {
            return apiError('修改失败');
        }
    }
    
    
    #[Permission('删除')]
    public function delete()
    {
        if (request()->method() === 'DELETE') {
            $id = request()->get('id', 0);
            if ($this->model->delete($id) !== false) {
                return apiSuccess('删除成功');
            } else {
                return apiError('删除失败');
            }
        }
        return apiError('删除失败');
        
    }

    #[Permission('获取办事处')]
    public function getData()
    {
        $data = $this->model->where('parent_id', '=', 2)->where('status', 1)->order('list_order asc,create_time desc')->select()->toArray();
        return apiSuccess('ok', $data);
    }
    
    
}